import json
import os
import shutil


def printPt(str):
    print("PT: " + str)


def getConfig():
    with open("config.con", "r") as fr:
        jsonObj = json.load(fr)
    inputapkname = jsonObj["apkname"]
    apktool = jsonObj["apktoolversion"] + ".jar"
    start_step = jsonObj["start_step"]
    return inputapkname, apktool, start_step


def copyFiles(sourceDir, targetDir, file_type=""):
    for f in os.listdir(sourceDir):
        sourceF = os.path.join(sourceDir, f)
        targetF = os.path.join(targetDir, f)
        if os.path.isfile(sourceF):
            if not os.path.exists(targetDir):
                os.makedirs(targetDir)
            if os.path.exists(targetF):
                os.remove(targetF)
            if file_type == "":
                shutil.copyfile(sourceF, targetF)
            elif file_type == "apk" and sourceF.endswith(file_type):
                shutil.copyfile(sourceF, targetF)
        if os.path.isdir(sourceF):
            copyFiles(sourceF, targetF)


def deleteDir(targetDir):
    for f in os.listdir(targetDir):
        targetF = os.path.join(targetDir, f)
        if os.path.isfile(targetF):
            if os.path.exists(targetF):
                os.remove(targetF)
    os.removedirs(targetDir)


def subStr(sourceStr, startStr, endStr):
    index1 = 0
    index2 = 0
    str = ""
    index1 = sourceStr.find(startStr, index2)
    index2 = sourceStr.find(endStr, index1 + len(startStr)) + len(endStr)
    while index1 != -1 and index2 != -1:
        str += sourceStr[index1:index2] + "\n"
        index1 = sourceStr.find(startStr, index2)
        index2 = sourceStr.find(endStr, index1 + len(startStr)) + len(endStr)
    return str


def get_files_list(directory, file_type=".apk"):
    file_list = []
    for f_root, f_dirs, f_files in os.walk(directory):
        for file_name in f_files:
            if (
                file_name.endswith(file_type)
                # and file_name.find("instantapp-release") > 0
            ):
                file_list.append(os.path.join(f_root, file_name))
    return file_list


def get_files_xml_list(directory, file_type=".xml"):
    file_list = []
    for f_root, f_dirs, f_files in os.walk(directory):
        for file_name in f_files:
            if file_name.endswith(file_type):
                file_list.append(os.path.join(f_root, file_name))
    return file_list


def get_files_css_list(directory, file_type=".css"):
    file_list = []
    for f_root, f_dirs, f_files in os.walk(directory):
        for file_name in f_files:
            if file_name.endswith(file_type):
                file_list.append(os.path.join(f_root, file_name))
    return file_list
